package com.hspedu.newData.dmsxl.字符串;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-29 
 * @Version: 1.0
 */

public class LC151反转字符串中的字词 {

    public String reverseWords(String s) {

        if (s.length() == 1){
            if (s.equals(" ")) return "";
            else return s;
        }

        int i = 0;
        int j = s.length() - 1;

        List<String> list = new ArrayList<>();
        while(i<j){
            while(s.charAt(j) == ' ' && i<j){
                j--;
            }
            int right = j;
            while (s.charAt(right)!=' ' && i<right){
                right--;
            }

            if (right != j){
                if (right==0){
                    list.add(s.substring(right,j+1));
                }else {
                    list.add(s.substring(right+1,j+1));
                }
            }
            while (s.charAt(i) == ' ' && i<right){
                i++;
            }
            int left = i;
            while (s.charAt(left) != ' ' && left < right){
                left++;
            }
            if (left != i){
                list.add(s.substring(i,left));
            }
            i = left;
            j = right;
        }

        StringBuilder res = new StringBuilder();

        for (int k = 0; k < list.size(); k++) {
            if (k % 2 == 0){
                res.append(list.get(k) + " ");
            }
        }
        for (int k = list.size() - 1; k >= 0; k--) {
            if (k % 2 != 0){
                res.append(list.get(k) + " ");
            }
        }
        res.deleteCharAt(res.length()-1);
        return res.toString();
    }

    @Test
    public void test() {
        // 测试代码

        String s = reverseWords("a");

        System.out.println(s);
    }
}
